package com.jxltech.krpano.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by feng on 2020/8/29 0029
 */

@AllArgsConstructor
@RestController
@Slf4j
public class ApiController {

	@Autowired
	private ApiService apiService;

	@GetMapping("info/{name}")
	public AjaxResult getFormInfo(@PathVariable String name) {
		return AjaxResult.success(apiService.getFormInfo(name));
	}

	/**
	 * 保存基本信息
	 * @return
	 * @throws Exception
	 */
	@PostMapping("save")
	public AjaxResult save(@RequestBody String body) throws Exception {
		JSONObject jsonObject = JSONObject.parseObject(body);
		apiService.saveForm(jsonObject);
		return AjaxResult.success();
	}

	/**
	 *	提交
	 * @return
	 * @throws Exception
	 */
	@PostMapping("submit")
	public AjaxResult submit(@RequestBody String body) throws Exception {
		JSONObject jsonObject = JSONObject.parseObject(body);
		apiService.submit(jsonObject);
		return AjaxResult.success();
	}

	@PostMapping("reset/{name}")
	public AjaxResult reset(@PathVariable String name) {
		log.info("reset info = {}", name);
		apiService.reset(name);
		return AjaxResult.success();
	}

	@PostMapping("delete/{name}/{type}/{fileName}")
	public AjaxResult deleteFile(@PathVariable String name, @PathVariable String type, @PathVariable String fileName) {
		log.info("delete info name = {}, type = {}, fileName = {}", name, type, fileName);
		apiService.deleteFile(name, type, fileName);
		return AjaxResult.success();
	}

	@PostMapping("uploadFile/{type}/{name}")
	public AjaxResult upload(@PathVariable String name, @PathVariable String type, MultipartFile file) throws Exception {
		apiService.saveUploadFile(name, type, file);
		return AjaxResult.success();
	}

	@GetMapping("list/{type}/{name}")
	public AjaxResult list(@PathVariable String name, @PathVariable String type) {
		List<HashMap> resultList = Lists.newArrayList();
		String[] list = apiService.list(name, type);
		if (list != null) {
			resultList = Arrays.asList(list).stream().map(item -> {
				HashMap map = new HashMap();
				map.put("fileName", item);
				return map;
			}).collect(Collectors.toList());
		}
		return AjaxResult.success(resultList);
	}

	@GetMapping("partition/{areaId}")
	public AjaxResult getPartitions(@PathVariable String areaId) {
		return AjaxResult.success(apiService.getPartitions(areaId));
	}

	@GetMapping("templates")
	public AjaxResult getTemplates() {
		return AjaxResult.success(apiService.getTemplates());
	}

}
